<template>
  <div class="app_container">
    <appHeader />
    <div class="container">
      <div class="home">
        <main class="main">
          <div class="formData">
            <div class="active">
              <img :src="`${baseUrl}${gameInfo.imgUrl}`">
              <div>{{ gameInfo.gameName }}</div>
            </div>
            <div style="width: 100%;">
              <ul class="formData-list">
                <li>
                  <div class="sub-title">{{ gameInfo.topupMode === '验证码' ? '手机号' : '充值账号' }}</div>
                  <div v-if="model.topupAccount">{{ model.topupAccount }}</div>
                  <div v-else>暂无信息</div>
                </li>
                <li>
                  <div class="sub-title">设备类型</div>
                  <div v-if="deciceType">{{ deciceType }}</div>
                  <div v-else>暂无信息</div>
                </li>
              </ul>
              <ul v-if="gameInfo.topupMode === '扫码'" class="formData-list">
                <li>
                  <div class="sub-title">游戏昵称</div>
                  <div>暂无信息</div>
                </li>
                <li>
                  <div class="sub-title">账号类型</div>
                  <div v-if="model.accountType">{{ model.accountType }}</div>
                  <div v-else>暂无信息</div>
                </li>
              </ul>
            </div>
          </div>
          <div class="main2">
            <el-form :ref="refName" :model="model" :rules="rules" label-width="82px" class="updateForm">
              <el-form-item v-if="codeIsOK" :label="gameInfo.topupMode === '验证码' ? '手机号:' : '充值账号:'" prop="topupAccount">
                <el-input v-model.number="model.topupAccount" clearable placeholder="请输入" />
              </el-form-item>
              <template v-if="gameInfo.topupMode === '验证码' && codeIsOK">
                <el-form-item label="验证码:" prop="verificationCode">
                  <div class="boxVerificationCode">
                    <el-input v-model="model.verificationCode" clearable placeholder="请输入" />
                    <el-button type="success" :disabled="disabledSendCode" round @click="sendCodeClick">发送验证码</el-button>
                  </div>
                  <div>倒计时/有效期：{{ countDown }}秒</div>
                </el-form-item>
               </template>
              <template v-if="gameInfo.topupMode === '扫码'">
                <el-form-item label="账号类型:" prop="accountType">
                  <el-radio-group v-model="model.accountType">
                    <el-radio v-for="(item, index) in accountTypeList" :key="index" :label="item.value">{{ item.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="游戏区服:" prop="learningStatus">
                  <el-select v-model="model.learningStatus" clearable placeholder="请选择">
                    <el-option label="手Q1" value="手Q1" />
                    <el-option label="手Q2" value="手Q2" />
                  </el-select>
                </el-form-item>
              </template>
              <el-form-item label="激活码:" prop="code">
                <div class="boxCode">
                  <el-input v-model="model.code" clearable placeholder="请输入" />
                  <el-button type="success" round @click="checkCode">检测激活码</el-button>
                </div>
              </el-form-item>
              <template v-if="codeIsOK">
                <el-button icon="el-icon-circle-check" type="primary" @click="nextClick">下一步</el-button>
                <el-button icon="el-icon-refresh" @click="resetForm">重置表单</el-button>
                <el-button class="goIndex" icon="el-icon-back" @click="goIndex">回首页</el-button>
              </template>
            </el-form>
          </div>
          <!-- v-if="textHint" -->
          <div v-if="textHint" class="textHint">{{ `状态：${stateNum}` }}, {{ textHint }}</div>
          <!-- v-if="stateNum === 5 || stateNum === '5'" -->
          <img v-if="stateNum === 5 || stateNum === '5'" class="imgHint" :src="imgHint" alt="无图片">
        </main>
      </div>
    </div>
    <hintDialog ref="hintDialog" />
  </div>
</template>

<script>
import appHeader from './components/appHeader.vue'
import hintDialog from './components/hintDialog.vue'
import { getAction } from '@/api/manage'
import { validatorPhone } from '@/utils/validate'
import { mapState } from 'vuex'
export default {
  components: {
    appHeader,
    hintDialog
  },
  mixins: [],
  props: {},
  data() {
    return {
      model: {},
      deciceType: '',
      refName: 'ruleForm',
      textHint: '',
      imgHint: '',
      stateNum: null,
      disabledSendCode: true,
      accountTypeList: [],
      selectStateiIntervalId: null,
      countDownSetInterval: null,
      countDown: 60,
      codeIsOK: false,
      rules: {
        topupAccount: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatorPhone,  message: '手机号格式不对', trigger: 'blur' }
        ],
        accountType: [
          { required: true, message: '请选择账号类型', trigger: 'change' }
        ],
        learningStatus: [
          { required: true, message: '请选择游戏区服', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入激活码', trigger: 'blur' }
        ]
      },
      gameList: []
    }
  },
  computed: {
    ...mapState({
      gameInfo: state => state.index.gameInfo
    }),
    baseUrl() {
      if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
        return ''
      } else {
        return 'http://124.223.214.5:199'
      }
    }
  },
  watch: {
    'model.topupAccount': {
      handler(v) {
        const regMobile = /(^1[3-9]\d{9}$)/
        this.disabledSendCode = !regMobile.test(v)
      }
    },
    countDown: {
      handler(v) {
        if (v <= 0) {
          clearInterval(this.countDownSetInterval)
          this.countDownSetInterval = null
          // console.log('监听countDown 清除后 this.countDownSetInterval', this.countDownSetInterval)
          this.disabledSendCode = false
          this.countDown = 60
        }
      }
    }
  },
  created() {
    // 存在本地缓存展示出来
    const orderInfo = localStorage.getItem('orderInfo')
    if (orderInfo) {
      const obj = JSON.parse(orderInfo)
      this.$set(this.model, 'topupAccount', obj.topupAccount)
      this.$set(this.model, 'code', obj.code)
    }
    console.log('this.model', this.model)
    console.log('gameInfo', this.gameInfo)
    this.getDeciceType() /// 获取设备类型
    if (!this.gameInfo.gameName) {
      this.$router.push('/index')
    } else {
      this.getAccountTypeList()
    }
  },
  mounted() {},
  methods: {
    // 检测激活码/激活码 是否可用
    async checkCode() {
      if (!this.model.code) {
        this.$message.warning('请输入激活码')
        return
      }
      const p = {
        gid: this.gameInfo.id,
        code: this.model.code,
        topupAccount: this.model.topupAccount
      }
      this.$store.dispatch('app/setLoading', true)
      const res = await getAction(`script/redeemCodeList.aspx?action=checkCode`, p).finally(() => {
        this.$store.dispatch('app/setLoading', false)
      })
      if (res.code === 1) {
        this.$message.success(res || '操作成功！')
        this.codeIsOK = true
        if (this.model.topupAccount) {
          console.log('存在手机号说明 保存过上次信息')
          this.disabledSendCode = true
          this.selectStateiIntervalId = setInterval(() => {
            this.selectState()
          }, 5000)
        }
      } else {
        this.$message.warning(res || '操作失败！')
        this.codeIsOK = false
      }
    },
    // 申请发送验证码
    async sendCodeClick() {
      if (!this.model.topupAccount) {
        this.$message.warning('请输入手机号！')
        return
      }
      if (!this.model.code) {
        this.$message.warning('请输入激活码！')
        return
      }
      // await this.checkCode()
      if (!this.codeIsOK) {
        return
      }
      this.disabledSendCode = true
      this.$store.dispatch('app/setLoading', true)
      getAction(`http://61.171.105.50:5656?ly=pc&jkmc=yzm_${this.gameInfo.prefix}&sjh=${this.model.topupAccount}&jhm=${this.model.code}`, {}).then((res) => {
        if (res === 1 || res === '1') {
          this.selectStateiIntervalId = setInterval(() => {
            this.selectState()
          }, 5000);
          this.$message.success('正在处理中...')
          this.textHint = '正在处理中...'
          // 存储订单信息到浏览器本地
          localStorage.setItem('orderInfo', JSON.stringify({
            topupAccount: this.model.topupAccount,
            code: this.model.code
          }))
        } else {
          this.$message.warning(res || '操作失败！')
          this.disabledSendCode = false
        }
      }).finally(() => {
        this.$store.dispatch('app/setLoading', false)
      })
    },
    // 查状态
    selectState() {
      getAction(`http://61.171.105.50:5656?ly=pc&&jkmc=ztcx&sjh=${this.model.topupAccount}&jhm=${this.model.code}`, {}).then((res) => {
        console.log('查状态结果', res)
        this.stateNum = res
        if (res === 0 || res === '0') { // 0 = 手机号或激活码错误
          this.$message.warning('手机号或激活码错误!')
          this.textHint = '手机号或激活码错误'
          this.disabledSendCode = false
          this.$refs.hintDialog.visible = false
          clearInterval(this.selectStateiIntervalId) // 停止循环调用查状态的接口
        } else if (res === 1 || res === '1') { // 1 = 服务器接收成功
          this.textHint = '服务器接收成功'
          this.$message.success('服务器接收成功')
        } else if (res === 2 || res === '2') { // 2=申请发送验证码
          this.$message.success('申请发送验证码', res)
          this.$refs.hintDialog.visible = false
          this.textHint = '申请发送验证码'
        } else if (res === 3 || res === '3') { // 3=验证码超时 或者 错误
          this.$message.success('验证码超时')
          this.textHint = '验证码超时'
          this.$refs.hintDialog.visible = false
          this.disabledSendCode = false
          clearInterval(this.selectStateiIntervalId)
        } else if (res === 4 || res === '4') { // 4=等待客户输入验证码
          this.$refs.hintDialog.visible = false
          this.handleInputCode()
        } else if (res === 5 || res === '5') { // 5=充值完成
          this.$message.success('充值完成')
          this.textHint = '充值完成'
          this.showHintModel({ textHint: this.textHint, stateNum: res })
          this.disabledSendCode = false
          clearInterval(this.selectStateiIntervalId)
          // 充值完成 新增记录
          this.topupOk()
          // 成功图片显示
          this.imgHint = `http://124.223.214.5:100/Upfile/Images/${this.gameInfo.prefix}_${this.model.code}.jpg`
          this.showHintModel({ textHint: this.textHint, stateNum: res, imgHint: this.imgHint })
          localStorage.setItem('orderInfo', '')
          // 展示返回图片
        } else if (res === 6 || res === '6') { // 6=充值失败
          this.textHint = '充值失败，请联系管理员'
          this.$message.warning('充值失败，请联系管理员')
          this.showHintModel({ textHint: this.textHint, stateNum: res })
          this.disabledSendCode = false
          localStorage.setItem('orderInfo', '')
          clearInterval(this.selectStateiIntervalId)
        } else if (res === 7 || res === '7') { // 7=充值中
          this.$message.success('充值中，请等待')
          this.textHint = '充值中，请等待'
          this.showHintModel({ textHint: this.textHint, stateNum: res })
        } else if (res === 8 || res === '8') { // 8=等待状态
          this.$message.success('等待服务端处理中...')
          this.textHint = '等待服务端处理中...'
          this.showHintModel({ textHint: this.textHint, stateNum: res })
        } else {
          this.textHint = '状态错误, 不存在该状态: ' + res
          this.disabledSendCode = false
          clearInterval(this.selectStateiIntervalId)
          this.$message.warning('操作失败！')
        }
      })
    },
    // 处理服务端已发送验证码 等待客户输入
    handleInputCode() {
      this.$message.success('验证码已发送至你的手机，等待输入验证码中...')
      this.textHint = '验证码已发送至你的手机，等待输入验证码，输入后点击 下一步'
      console.log('验证码已发送至你的手机，等待输入验证码中...')
      // 输入验证码倒计时
      console.log('循环调用查状态的接口', this.selectStateiIntervalId)
      clearInterval(this.selectStateiIntervalId)
      console.log('倒计时线程', this.countDownSetInterval)
      if (!this.countDownSetInterval) {
        this.disabledSendCode = true
        this.countDownSetInterval = setInterval(() => {
          this.countDown--
        }, 1000);
      }
    },
    // 下一步
    nextClick() {
      console.log('提交表单this.model', this.model)
      this.$refs[this.refName].validate((valid) => {
        if (valid) {
          this.$store.dispatch('app/setLoading', true)
          getAction(`http://61.171.105.50:5656?ly=pc&jkmc=yzm_tysryzm&sjh=${this.model.topupAccount}&jhm=${this.model.code}&yzm=${this.model.verificationCode}`, {}).then((res) => {
            if (res === '1' || res === 1) {
              this.textHint = '执行下一步'
              this.showHintModel({ textHint: this.textHint, stateNum: res })
              // 改状态为8
              getAction(`http://61.171.105.50:5656?ly=yd&jkmc=ztgg&sjh=${this.model.topupAccount}&jhm=${this.model.code}&zt=8`, {}).then((res) => {
                if (res === '1' || res === 1) {
                  this.textHint = '等待服务端处理...'
                  this.showHintModel({ textHint: this.textHint, stateNum: res })
                  this.selectStateiIntervalId = setInterval(() => {
                    console.log('开始巡检查询状态')
                    this.selectState()
                  }, 5000);
                } else {
                  this.$message.warning('操作失败！')
                  this.disabledSendCode = false
                }
              })
              this.$message.success('执行下一步成功！')
            } else {
              this.$message.warning('执行下一步失败！')
              this.disabledSendCode = false
            }
          }).finally(() => {
            this.$store.dispatch('app/setLoading', false)
          })
        }
      })
    },
    // 充值完成
    topupOk() {
      const p = {
        deviceType: this.deciceType,
        gid: this.gameInfo.id,
        code: this.model.code,
        topupAccount: this.model.topupAccount
      }
      this.$store.dispatch('app/setLoading', true)
      getAction('script/redeemCodeList.aspx?action=exchange', p).then((res) => {
        if (res.code === 1) {
          this.textHint = '充值成功！'
          this.$message.success(res.message || '操作成功！')
        } else {
          this.$message.warning(res.message || '操作失败！')
        }
      }).finally(() => {
        this.$store.dispatch('app/setLoading', false)
      })
    },
    // 显示弹窗
    showHintModel(obj) {
      this.$refs.hintDialog.show({
        text: obj.textHint,
        stateNum: obj.stateNum,
        imgHint: obj.imgHint,
        time: this.getFormattedDate()
      })
    },
    // 重置表单
    resetForm() {
      this.imgHint = `http://124.223.214.5:100/Upfile/Images/qqyy_16CD55A12F004C6DADDB9BD27C49047B.jpg`
      this.$refs.hintDialog.show({
        text: '提示文字',
        stateNum: 5,
        imgHint: this.imgHint,
        time: this.getFormattedDate()
      })
      // 存储订单信息到浏览器本地
      // localStorage.setItem('orderInfo', JSON.stringify({
      //   topupAccount: this.model.topupAccount,
      //   code: this.model.code
      // }))
      this.model = {}
      console.log('this.model', this.model)
    },
    // 回首页
    goIndex() {
      // this.imgHint = `http://124.223.214.5:100/Upfile/Images/${this.gameInfo.prefix}_${this.model.code}.jpg`
      // console.log('this.imgHint', this.imgHint)
      
      this.$router.push('/index')
    },
    // 获取账号类型
    getAccountTypeList() {
      this.accountTypeList = [
        { label: 'QQ', value: 'QQ' },
        { label: '微信', value: '微信' }
      ]
      // this.$store.dispatch('app/setLoading', true)
      // postAction('script/gameList.aspx?action=getGamneList', {}).then(res => {
      //   if (res.code === 1) {
      //     this.gameList = res.data || []
      //   } else {
      //     this.$message.warning(res.message || '操作失败！')
      //   }
      // }).catch(res => {
      //   this.$message.error(res.message || '操作失败！')
      // }).finally(() => {
      //   this.$store.dispatch('app/setLoading', false)
      // })
    },
    // 获取设备类型
    getDeciceType() {
      const ua = navigator.userAgent.toLowerCase()
      console.log('ua', ua)
      let os = ''
       // 检测操作系统
      if (ua.includes('win')) {
        os = 'Windows'
      } else if (ua.includes('mac')) {
        os = 'MacOS'
      } else if (ua.includes('linux')) {
        os = 'Linux'
      } else if (ua.includes('android')) {
        os = 'Android';
      } else if (ua.includes('ios')) {
        os = 'iOS'
      } else {
        os = '未知'
      }
      this.deciceType = os
    },
    getFormattedDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  },
  beforeDestroy() {
    if (this.countDownSetInterval) {
      clearInterval(this.countDownSetInterval)
    }
    if (this.selectStateiIntervalId) {
      clearInterval(this.selectStateiIntervalId)
    }
  }
}
</script>

<style lang="scss" scoped>
.boxVerificationCode{
  display: flex;
  .el-input{
    margin-right: 10px;
  }
}
.boxCode{
  // display: flex;
  .el-input{
    margin-bottom: 10px;
    margin-right: 10px;
  }
}
.app_container{
  width: 100%;
  // height: 100%;
  background-image: url('../assets/home_bg.png');
  background-size: cover;
}
.container{
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  .home{
    width: 100%;
    max-width: 800px;
    height: 100vh;
    box-sizing: border-box;
    padding: 0 10px;
    .main{
      width: 100%;
      background-color: #fff3;
      padding: 10px;
      color: #666;
      box-sizing: border-box;
      border-radius: 10px;
      .formData{
        display: flex;
        align-items: center;
        .active{
          img{
            width: 80px;
            height: 80px;
            border-radius: 10px;
          }
          div:nth-child(2){
            text-align: center;
          }
        }
        div:nth-child(2){
          .formData-list{
            list-style: none;
            display: block;
            display: flex;
            justify-content: space-between;
            li{
              flex: 1;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              .sub-title{
                font-size: 14px;
                color: #409eff;
                margin-bottom: 10px;
              }
            }
          }
        }
      }
      .main2{
        width: 100%;
        background-color: #fff3;
        padding: 10px;
        color: #666;
        box-sizing: border-box;
        border-radius: 10px;
      }
    }
  }
}
::v-deep .el-form-item__label{
  color: #666;
  // font-size: 14px;
}
.el-select{
  width: 100%;
}
.goIndex{
  margin-left: 5%;
}
.el-button--medium{
  padding: 10px;
}
.imgHint{
  transform: translateX(50%);  
  width: 50%;
  height: 50%;
}
</style>>